﻿using CodeMapper.Commons;
using CodeMapper.Metas;
using System;
using System.Collections.Generic;

namespace CodeMapper.Mappers
{
    internal class CustomMapper : BaseMapper
    {
        private Func<object, object> innerMapper;
        private readonly TypePair pair;

        public CustomMapper(TypePair pair)
        {
            innerMapper = CustomMapper.Get(pair);
            this.pair = pair;
        }
        protected override object MapCore(object source, object target, int depth)
        {
            try
            {
                return innerMapper(source);
            }
            catch(Exception ex)
            {
                var msg = $"CustomMapper自定义转换({pair})失败 --> {ex.Message}";
                throw new Exception(msg, ex);
            }
        }

        internal static void Add(TypePair pair, Func<object, object> mapper)
        {
            Converter.Cache.Add(pair, mapper);
        }

        internal static Func<object, object> Get(TypePair pair)
        {
            return Converter.Cache.Get(pair);
        }

        internal static bool Has(TypePair pair)
        {
            return Converter.Cache.HasKey(pair);
        }
        internal static void Remove(TypePair pair)
        {
            Converter.Cache.Remove(pair);
        }
    }
}
